package com.xujl.fastlib.utils;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
import android.text.TextUtils;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.CustomViewTarget;
import com.bumptech.glide.request.transition.Transition;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * @author x
 * @Description
 */
public class ImgHelper {
    public static void loadImgNormal (Context context, ImageView imageView, Object res) {
        if (res == null || StringUtils.isEmpty(res.toString())) {
            return;
        }
        Glide.with(context).load(res).into(imageView);
    }

    /**
     * 根据图片路径设置tag
     *
     * @param context
     * @param imageView
     * @param res
     */
    public static void loadImgNormalForTag (Context context, final ImageView imageView, final Object res) {
        Glide.with(context).load(res)
                .into(new CustomViewTarget<ImageView, Drawable>(imageView) {
                    @Override
                    public void onLoadFailed (@Nullable Drawable errorDrawable) {
                    }

                    @Override
                    public void onResourceReady (@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                        if (StringUtils.equals(imageView.getTag().toString(), res.toString())) {
                            imageView.setImageDrawable(resource);
                        }
                    }

                    @Override
                    protected void onResourceCleared (@Nullable Drawable placeholder) {
                    }
                });
    }

    public static void loadCircleImg (Context context, ImageView imageView, Object res) {
        Glide.with(context).load(res)
                .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                .into(imageView);
    }

    /**
     * 根据图片路径设置tag防止网络图片错位
     *
     * @param context
     * @param imageView
     * @param res
     */
    public static void loadCircleImgForTag (Context context, final ImageView imageView, final Object res) {
        Glide.with(context).load(res)
                .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                .into(new CustomViewTarget<ImageView, Drawable>(imageView) {
                    @Override
                    public void onLoadFailed (@Nullable Drawable errorDrawable) {
                    }

                    @Override
                    public void onResourceReady (@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                        if (StringUtils.equals(imageView.getTag().toString(), res.toString())) {
                            imageView.setImageDrawable(resource);
                        }
                    }

                    @Override
                    protected void onResourceCleared (@Nullable Drawable placeholder) {
                    }
                });
    }

    public static Bitmap getBitmapFormResources (Context context, int resId) {
        return BitmapFactory.decodeResource(context.getResources(), resId);
    }

    public static Drawable getDrawableFromResources (Context context, int resId) {
        return context.getResources().getDrawable(resId);
    }

    public static Drawable getDrawbleFormBitmap (Context context, Bitmap bitmap) {
        return new BitmapDrawable(context.getResources(), bitmap);
    }

    public static Bitmap getBitmapFormDrawable (Context context, Drawable drawable) {
        Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
                drawable.getIntrinsicHeight(), drawable.getOpacity() != PixelFormat.OPAQUE
                        ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        //设置绘画的边界，此处表示完整绘制
        drawable.draw(canvas);
        return bitmap;
    }

    /**
     * 将相册选择的数据转化成真实图片路径
     *
     * @param context
     * @param uri
     * @return
     */
    public static String getRealFilePath (Context context, Uri uri) {

        if (null == uri) return null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return getFilePathForN(context, uri);
        }
        final String scheme = uri.getScheme();
        String realPath = null;
        if (scheme == null)
            realPath = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            realPath = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri,
                    new String[]{MediaStore.Images.ImageColumns.DATA},
                    null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        realPath = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        if (TextUtils.isEmpty(realPath)) {
            if (uri != null) {
                String uriString = uri.toString();
                int index = uriString.lastIndexOf("/");
                String imageName = uriString.substring(index);
                File storageDir;

                storageDir = Environment.getExternalStoragePublicDirectory(
                        Environment.DIRECTORY_PICTURES);
                File file = new File(storageDir, imageName);
                if (file.exists()) {
                    realPath = file.getAbsolutePath();
                } else {
                    storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
                    File file1 = new File(storageDir, imageName);
                    realPath = file1.getAbsolutePath();
                }
            }
        }
        return realPath;
    }

    /**
     * android7.0以上处理方法
     */
    private static String getFilePathForN (Context context, Uri uri) {
        try {
            Cursor returnCursor = context.getContentResolver().query(uri, null, null, null, null);
            int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
            returnCursor.moveToFirst();
            String name = (returnCursor.getString(nameIndex));
            File file = new File(context.getFilesDir(), name);
            InputStream inputStream = context.getContentResolver().openInputStream(uri);
            FileOutputStream outputStream = new FileOutputStream(file);
            int read = 0;
            int maxBufferSize = 1 * 1024 * 1024;
            int bytesAvailable = inputStream.available();

            int bufferSize = Math.min(bytesAvailable, maxBufferSize);

            final byte[] buffers = new byte[bufferSize];
            while ((read = inputStream.read(buffers)) != -1) {
                outputStream.write(buffers, 0, read);
            }
            returnCursor.close();
            inputStream.close();
            outputStream.close();
            return file.getPath();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
